// 存储脚本运行状态
const runningScripts = new Set();
let statusCheckInterval = null;

// 页面加载时检查所有脚本状态
document.addEventListener('DOMContentLoaded', () => {
    // 获取所有脚本项
    const scriptItems = document.querySelectorAll('.script-item');
    const scriptNames = Array.from(document.querySelectorAll('.scripts-table tbody tr:not(.output-row) strong')).map(el => el.textContent);
    
    // 清除可能存在的旧定时器
    if (statusCheckInterval) {
        clearInterval(statusCheckInterval);
    }

    // 初始检查所有脚本状态
    checkAllScriptsStatus(scriptNames);

    // 设置定期检查
    statusCheckInterval = setInterval(() => {
        checkAllScriptsStatus(scriptNames);
    }, 5000); // 每5秒检查一次所有脚本状态
});

// 检查所有脚本状态
function checkAllScriptsStatus(scriptNames) {
    scriptNames.forEach(name => {
        checkScriptStatus(name);
    });
}

// 检查单个脚本运行状态
function checkScriptStatus(scriptName) {
    fetch(`/script_status/${scriptName}`)
    .then(response => {
        if (!response.ok) {
            throw new Error('Script status check failed');
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            return;
        }

        const outputContainer = document.getElementById(`output-${scriptName}`);
        const runBtn = document.querySelector(`[onclick="runScript('${scriptName}')"]`);
        
        if (data.is_running) {
            // 脚本正在运行
            if (!runningScripts.has(scriptName)) {
                runningScripts.add(scriptName);
                if (runBtn) {
                    runBtn.disabled = true;
                }
                if (outputContainer) {
                    restoreRunningState(scriptName, outputContainer, data);
                }
            } else {
                // 更新现有输出
                updateScriptOutput(scriptName, data);
            }
        } else {
            // 脚本已停止
            if (runningScripts.has(scriptName)) {
                runningScripts.delete(scriptName);
                if (runBtn) {
                    runBtn.disabled = false;
                }
                if (outputContainer && data.returncode !== null) {
                    updateScriptOutput(scriptName, data, true);
                }
            }
        }
    })
    .catch(error => {
        console.error('检查脚本状态失败:', error);
    });
}

// 更新脚本输出
function updateScriptOutput(scriptName, data, isComplete = false) {
    const outputContainer = document.getElementById(`output-${scriptName}`);
    if (!outputContainer) return;

    let statusSpan = outputContainer.querySelector('.run-status');
    const outputArea = outputContainer.querySelector('.output-area');
    
    if (!statusSpan) {
        statusSpan = document.createElement('span');
        statusSpan.className = 'run-status';
        outputContainer.insertBefore(statusSpan, outputContainer.firstChild);
    }

    if (!outputArea) {
        const newOutputArea = document.createElement('pre');
        newOutputArea.className = 'output-area';
        outputContainer.appendChild(newOutputArea);
    }

    // 更新状态显示
    if (isComplete) {
        const hasError = data.stderr.length > 0;
        const success = data.returncode === 0 && !hasError;
        statusSpan.innerHTML = `<span class="status-dot ${success ? 'success' : 'error'}"></span> 
                            ${success ? '运行完成' : '运行异常'} (返回码: ${data.returncode})`;
    } else {
        statusSpan.innerHTML = '<span class="status-dot running"></span> 运行中';
    }

    // 更新输出内容
    if (outputArea) {
        let allLines = [];
        
        // 如果有更多输出，显示省略号
        const totalLines = data.total_lines.stdout + data.total_lines.stderr;
        if (totalLines > 5) {
            allLines.push(`<div class="output-ellipsis">... (共 ${totalLines} 行输出)</div>`);
        }
        
        // 添加标准输出
        data.stdout.forEach(line => {
            allLines.push(line);
        });
        
        // 添加错误输出
        data.stderr.forEach(line => {
            allLines.push(`<span class="error-output">${line}</span>`);
        });
        
        outputArea.innerHTML = allLines.join('\n');
        outputArea.scrollTop = outputArea.scrollHeight;
    }

    // 显示输出容器
    outputContainer.style.display = 'block';
}

// 恢复运行状态的UI
function restoreRunningState(scriptName, outputContainer, initialData) {
    outputContainer.style.display = 'block';
    outputContainer.innerHTML = '';
    
    // 创建状态span
    const statusSpan = document.createElement('span');
    statusSpan.className = 'run-status';
    statusSpan.innerHTML = '<span class="status-dot running"></span> 运行中';
    
    // 创建停止按钮
    const stopBtn = document.createElement('button');
    stopBtn.className = 'stop-btn';
    stopBtn.textContent = '停止';
    stopBtn.onclick = () => stopScript(scriptName);
    
    // 创建输出区域
    const outputArea = document.createElement('pre');
    outputArea.className = 'output-area';
    
    // 添加元素到容器
    outputContainer.appendChild(statusSpan);
    outputContainer.appendChild(stopBtn);
    outputContainer.appendChild(outputArea);
    
    // 更新输出内容
    updateScriptOutput(scriptName, initialData);
}

// 修改runScript函数
function runScript(scriptName) {
    // 如果脚本已经在运行，直接返回
    if (runningScripts.has(scriptName)) {
        console.warn('脚本已在运行中');
        return;
    }

    const outputContainer = document.getElementById(`output-${scriptName}`);
    const fileSelect = document.getElementById(`file-${scriptName}`);
    const selectedFile = fileSelect.value;
    const runBtn = document.querySelector(`[onclick="runScript('${scriptName}')"]`);
    const statusSpan = document.createElement('span');
    statusSpan.className = 'run-status';
    statusSpan.innerHTML = '<span class="status-dot running"></span> 正在启动...';

    // 创建停止按钮
    const stopBtn = document.createElement('button');
    stopBtn.className = 'stop-btn';
    stopBtn.textContent = '停止';
    stopBtn.onclick = () => stopScript(scriptName);

    outputContainer.style.display = 'block';
    outputContainer.innerHTML = '';
    outputContainer.appendChild(statusSpan);
    outputContainer.appendChild(stopBtn);
    
    // 创建输出内容区域
    const outputArea = document.createElement('pre');
    outputArea.className = 'output-area';
    outputContainer.appendChild(outputArea);

    runBtn.disabled = true;

    // 启动脚本
    fetch(`/run_script/${scriptName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ file: selectedFile })
    }).then(response => response.json())
    .then(data => {
        if (data.error) {
            throw new Error(data.error);
        }
        
        console.log('脚本启动成功，开始轮询状态');
        runningScripts.add(scriptName);
        // 等待一小段时间再开始轮询，确保后端有时间初始化
        setTimeout(() => {
            pollScriptStatus(scriptName, outputArea, statusSpan, stopBtn, 0, 0);
        }, 500);
    })
    .catch(error => {
        console.error('启动脚本失败:', error);
        statusSpan.innerHTML = `<span class="status-dot error"></span> 运行失败`;
        runningScripts.delete(scriptName);
        runBtn.disabled = false;
        stopBtn.remove();
    });
}

// 修改stopScript函数
function stopScript(scriptName) {
    if (!runningScripts.has(scriptName)) {
        console.warn('脚本未在运行');
        return;
    }

    const outputContainer = document.getElementById(`output-${scriptName}`);
    const statusSpan = outputContainer.querySelector('.run-status');
    const stopBtn = outputContainer.querySelector('.stop-btn');
    
    fetch(`/stop_script/${scriptName}`, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error('停止脚本失败:', data.error);
            if (statusSpan) {
                statusSpan.innerHTML = `<span class="status-dot error"></span> 停止失败`;
            }
        } else {
            console.log('脚本已停止:', data.message);
            if (statusSpan) {
                statusSpan.innerHTML = `<span class="status-dot success"></span> 已停止`;
            }
            runningScripts.delete(scriptName);
            const runBtn = document.querySelector(`[onclick="runScript('${scriptName}')"]`);
            if (runBtn) {
                runBtn.disabled = false;
            }
            if (stopBtn) {
                stopBtn.remove();
            }
        }
    })
    .catch(error => {
        console.error('停止脚本请求失败:', error);
        if (statusSpan) {
            statusSpan.innerHTML = `<span class="status-dot error"></span> 停止失败`;
        }
    });
}

// 切换虚拟环境
function changeVenv(scriptName, venvName) {
    fetch(`/change_venv/${scriptName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ venv: venvName })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            // 显示成功消息
            const outputContainer = document.getElementById(`output-${scriptName}`);
            outputContainer.style.display = 'block';
            outputContainer.textContent = `已切换到${venvName ? venvName : '系统Python'}`;
            setTimeout(() => {
                outputContainer.style.display = 'none';
            }, 2000);
        }
    })
    .catch(error => {
        alert('切换虚拟环境失败: ' + error);
    });
}

// 格式化字节大小为人类可读格式
function formatBytes(bytes) {
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) return '0 B';
    const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

// 更新系统资源信息
function updateSystemResources() {
    fetch('/system_resources')
        .then(response => response.json())
        .then(data => {
            // 更新CPU信息
            document.getElementById('cpu-progress').style.width = `${data.cpu.percent}%`;
            document.getElementById('cpu-text').textContent = `${data.cpu.percent}%`;
            document.getElementById('cpu-cores').textContent = `核心数: ${data.cpu.cores}`;

            // 更新内存信息
            document.getElementById('memory-progress').style.width = `${data.memory.percent}%`;
            document.getElementById('memory-text').textContent = `${data.memory.percent}%`;
            document.getElementById('memory-details').textContent = 
                `已用: ${formatBytes(data.memory.used)} / 总计: ${formatBytes(data.memory.total)}`;

            // 更新磁盘信息
            document.getElementById('disk-progress').style.width = `${data.disk.percent}%`;
            document.getElementById('disk-text').textContent = `${data.disk.percent}%`;
            document.getElementById('disk-details').textContent = 
                `可用: ${formatBytes(data.disk.free)} / 总计: ${formatBytes(data.disk.total)}`;

            // 更新运行中的脚本数量
            document.getElementById('running-scripts').textContent = data.running_scripts;
        })
        .catch(error => console.error('获取系统资源信息失败:', error));
}

// 每5秒更新一次系统资源信息
setInterval(updateSystemResources, 5000);
// 页面加载时立即更新一次
document.addEventListener('DOMContentLoaded', updateSystemResources); 